<script setup>
import { ref, reactive } from 'vue'
import { empLoginApi, userLoginApi, adminLoginApi, userRegisterApi } from '@/api/login'
import { ElMessage} from 'element-plus'
import { useRouter } from 'vue-router'

// 登录表单数据
let loginForm = ref({username:'', password:'', role: 'user'}) // 默认用户登录
let router = useRouter()

// 注册相关状态
const registerDialogVisible = ref(false)
const registerForm = ref({
  username: '',
  password: '',
  name: '',
  gender: 1, // 默认男
  phone: ''
})

// 注册表单校验规则
const registerRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ]
})

// 注册表单引用
const registerFormRef = ref(null)

//登录
const login = async () => {
  let result
  
  try {
    // 根据用户选择的登录类型调用不同的API
    if (loginForm.value.role === 'employee') {
      result = await empLoginApi({username: loginForm.value.username, password: loginForm.value.password})
    } else if (loginForm.value.role === 'user') {
      result = await userLoginApi({username: loginForm.value.username, password: loginForm.value.password})
    } else if (loginForm.value.role === 'admin') {
      result = await adminLoginApi({username: loginForm.value.username, password: loginForm.value.password})
    }
    
    if (result.code) {// 登录成功
      ElMessage.success('登录成功')
      // 保存登录信息，包括用户类型
      const loginInfo = {
        ...result.data,
        role: loginForm.value.role
      }
      localStorage.setItem('loginUser', JSON.stringify(loginInfo))
      
      // 根据用户类型跳转到不同页面
      if (loginForm.value.role === 'admin') {
        router.push('/')// 管理员跳转到后台管理界面
      } else if (loginForm.value.role === 'employee') {
        // 员工也跳转到后台管理界面（原逻辑）
        router.push('/')
      } else {
        // 用户可以跳转到用户界面（如果有）
        router.push('/user')
      }
    } else {
      ElMessage.error(result.msg)
    }
  } catch (error) {
    ElMessage.error('登录失败，请重试')
  }
}

//取消
const cancel = () => {
  loginForm.value = {
    username: '',
    password: ''
  }
}

// 打开注册对话框
const openRegisterDialog = () => {
  registerDialogVisible.value = true
}

// 关闭注册对话框
const closeRegisterDialog = () => {
  registerDialogVisible.value = false
  // 重置表单
  if (registerFormRef.value) {
    registerFormRef.value.resetFields()
  }
}

// 注册
const register = async () => {
  // 表单校验
  try {
    await registerFormRef.value.validate()
    
    // 调用注册API
    const result = await userRegisterApi(registerForm.value)
    
    if (result.code) {
      ElMessage.success('注册成功，请登录')
      registerDialogVisible.value = false
      // 重置表单
      if (registerFormRef.value) {
        registerFormRef.value.resetFields()
      }
    } else {
      ElMessage.error(result.msg)
    }
  } catch (error) {
    // 表单校验失败或API错误都在这里处理
    ElMessage.error('注册失败，请重试')
  }
}
</script>

<template>
  <div id="container">
    <!-- 装饰元素 - 模拟汽车4S店标志背景 -->
    <div class="decorative-shapes">
      <div class="circle-shape"></div>
      <div class="rectangle-shape"></div>
    </div>
    
    <div class="login-form">
      <!-- 4S店标志区域 -->
      <div class="logo-section">
        <div class="car-logo">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 50" width="80" height="40">
            <rect x="10" y="25" width="80" height="15" rx="2" fill="#2c3e50"/>
            <circle cx="25" cy="40" r="7" fill="#34495e"/>
            <circle cx="75" cy="40" r="7" fill="#34495e"/>
            <path d="M15 25 C15 18 20 15 40 15 L60 15 C80 15 85 18 85 25" fill="#3498db"/>
            <path d="M40 15 L40 10 M60 15 L60 10" stroke="#ecf0f1" stroke-width="3"/>
          </svg>
        </div>
        <h1 class="title">汽车4S服务系统</h1>
        <p class="subtitle">专业服务 · 品质保障</p>
      </div>
      
      <el-form label-width="0">
        <!-- 用户类型选择 -->
        <el-form-item class="role-section">
          <el-radio-group v-model="loginForm.role" size="large" class="role-radio-group">
            <el-radio label="user" class="role-option inline-role">
              <div class="role-icon user-icon"></div>
              <span>客户</span>
            </el-radio>
            <el-radio label="employee" class="role-option inline-role">
              <div class="role-icon staff-icon"></div>
              <span>员工</span>
            </el-radio>
            <el-radio label="admin" class="role-option inline-role">
              <div class="role-icon admin-icon"></div>
              <span>管理员</span>
            </el-radio>
          </el-radio-group>
        </el-form-item>
        
        <!-- 登录表单项 -->
        <div class="login-inputs">
          <el-form-item prop="username" class="login-input-item">
            <el-input 
              v-model="loginForm.username" 
              placeholder="请输入用户名"
              prefix-icon="el-icon-user"
              size="large"
              class="custom-input"
            ></el-input>
          </el-form-item>
          
          <el-form-item prop="password" class="login-input-item">
            <el-input 
              type="password" 
              v-model="loginForm.password" 
              placeholder="请输入密码"
              prefix-icon="el-icon-lock"
              size="large"
              class="custom-input"
            ></el-input>
          </el-form-item>
        </div>

        <!-- 按钮区域 -->
        <div class="button-group">
          <el-button class="btn-register" type="info" @click="openRegisterDialog">注 册</el-button>
          <el-button class="btn-login" type="primary" @click="login">登 录</el-button>
          <el-button class="btn-reset" type="default" @click="cancel">重 置</el-button>
        </div>
      </el-form>
      
      <!-- 底部标语 -->
      <div class="footer-slogan">
        <p>用心服务每一位客户</p>
      </div>
    </div>
  </div>
  
  <!-- 注册对话框 -->
  <el-dialog
    v-model="registerDialogVisible"
    title="用户注册"
    width="400px"
    :close-on-click-modal="false"
    @close="closeRegisterDialog"
  >
    <el-form
      ref="registerFormRef"
      :model="registerForm"
      :rules="registerRules"
      label-width="80px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="registerForm.username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="registerForm.password" placeholder="请输入密码"></el-input>
      </el-form-item>
      
      <el-form-item label="姓名" prop="name">
        <el-input v-model="registerForm.name" placeholder="请输入姓名"></el-input>
      </el-form-item>
      
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="registerForm.gender">
          <el-radio label="1">男</el-radio>
          <el-radio label="2">女</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="registerForm.phone" placeholder="请输入手机号"></el-input>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeRegisterDialog">取 消</el-button>
        <el-button type="primary" @click="register">注 册</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
/* 全局容器样式 */
#container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
  position: relative;
  overflow: hidden;
}

/* 装饰性图形 */
.decorative-shapes {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: 0;
}

.circle-shape {
  position: absolute;
  width: 300px;
  height: 300px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.05);
  top: -100px;
  right: -100px;
}

.rectangle-shape {
  position: absolute;
  width: 400px;
  height: 400px;
  transform: rotate(45deg);
  background: rgba(255, 255, 255, 0.03);
  bottom: -200px;
  left: -200px;
}

/* 登录表单容器 */
.login-form {
  max-width: 450px;
  width: 100%;
  padding: 40px;
  border-radius: 16px;
  background: rgba(255, 255, 255, 0.95);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(8px);
  border: 1px solid rgba(255, 255, 255, 0.18);
  position: relative;
  z-index: 1;
  transition: all 0.3s ease;
}

.login-form:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

/* 标志和标题区域 */
.logo-section {
  text-align: center;
  margin-bottom: 35px;
}

.car-logo {
  margin-bottom: 15px;
  opacity: 0.9;
}

.title {
  font-size: 28px;
  font-family: 'Microsoft YaHei', sans-serif;
  color: #2c3e50;
  margin-bottom: 8px;
  font-weight: bold;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
}

.subtitle {
  font-size: 14px;
  color: #7f8c8d;
  font-weight: 500;
  letter-spacing: 1px;
}

/* 角色选择区域 */
.role-section {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ecf0f1;
}

.role-radio-group {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  flex-wrap: nowrap;
}

.role-option {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 30%;
  transition: all 0.3s ease;
  cursor: pointer;
  padding: 10px 0;
  border-radius: 8px;
}

.role-option:hover {
  background-color: rgba(236, 240, 241, 0.5);
}

.role-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #ecf0f1;
}

.user-icon::after {
  content: '👤';
  font-size: 20px;
}

.staff-icon::after {
  content: '👨‍💼';
  font-size: 20px;
}

.admin-icon::after {
  content: '🔧';
  font-size: 20px;
}

.role-option .el-radio__input:checked + .el-radio__label .role-icon {
  background-color: #3498db;
  color: white;
}

.role-option span {
  font-size: 14px;
  color: #2c3e50;
}

/* 确保角色选项在同一行 */
.role-radio-group .el-radio {
  display: inline-flex;
  margin: 0;
  padding: 0 10px;
  width: 33.33%;
  justify-content: center;
  align-items: center;
}

/* 输入框区域 */
.login-inputs {
  margin-bottom: 30px;
}

.login-input-item {
  margin-bottom: 20px;
}

.custom-input {
  width: 100%;
  height: 48px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.custom-input:focus {
  border-color: #3498db;
  box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
}

.custom-input .el-input__inner {
  border-radius: 8px;
  height: 100%;
  font-size: 15px;
  padding-left: 45px;
}

.custom-input .el-input__prefix {
  left: 15px;
}

/* 按钮组 */
.button-group {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.btn-register, .btn-login, .btn-reset {
  flex: 1;
  height: 45px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.btn-register {
  margin-right: 10px;
  background-color: #95a5a6;
  border-color: #95a5a6;
}

.btn-register:hover {
  background-color: #7f8c8d;
  border-color: #7f8c8d;
}

.btn-login {
  margin: 0 5px;
  background-color: #3498db;
  border-color: #3498db;
}

.btn-login:hover {
  background-color: #2980b9;
  border-color: #2980b9;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(52, 152, 219, 0.3);
}

.btn-reset {
  margin-left: 10px;
}

.btn-reset:hover {
  background-color: #ecf0f1;
}

/* 底部标语 */
.footer-slogan {
  text-align: center;
  margin-top: 20px;
}

.footer-slogan p {
  color: #7f8c8d;
  font-size: 12px;
  font-style: italic;
  letter-spacing: 0.5px;
}

/* 注册对话框样式调整 */
:deep(.el-dialog__header) {
  background-color: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  padding: 20px;
}

:deep(.el-dialog__title) {
  color: #2c3e50;
  font-size: 18px;
  font-weight: 500;
}

:deep(.el-dialog__body) {
  padding: 25px 20px;
}

:deep(.el-dialog__footer) {
  padding: 15px 20px 20px;
  border-top: 1px solid #e9ecef;
  background-color: #f8f9fa;
}

.dialog-footer {
  text-align: center;
}
</style>